<?php

class ImageTexter {
	
	private $text, $fontSize, $fontName, $fontColor, $bgColor, $height, $width, $style, $bgImagePath, $rotation, $borderSize=0, $borderColor;
	
	private $cachepath, $cachefile;
	
	private $isRendered;
	
	function __construct($text="", $fontSize = 12, $fontName="Arial", $fontColor="0x000000", $bgColor="0xffffff", $style="imageLink") {
		if($text) $this->setText($text);
		if($fontSize) { $this->setFontSize($fontSize); }
		if($fontName) { $this->setFontName($fontName); }
		if($fontColor) { $this->setFontColor($fontColor); }
		if($bgColor) { $this->setBgColor($bgColor); }
		if($style) { $this->setStyle($style); }
	}
	
	function setText($value) { $this->text = $value; }
	function setFontSize($value) { $this->fontSize = $value; }
	function setFontName($value) { $this->fontName = $value; }
	function setFontColor($value) { $this->fontColor = $value; }
	function setBgColor($value) { $this->bgColor = $value; }
	function setHeight($value) { $this->height = $value; }
	function setWidth($value) { $this->width = $value; }
	function setStyle($value) { $this->style = $value; }
	function setBgImagePath($fspath) { $this->bgImagePath = $fspath; }
	function setRotation($value) { if($value==0||$value==90||$value==180||$value==270) $this->rotation = $value; }
	function setBorderColor($value) { $this->borderColor = $value; }
	function setBorderSize($value) { $this->borderSize = $value; }
	
			
	function render() {
		
		$cfg = Runtime::getConfiguration();
		
		$fontspath = dirname(__FILE__). "/fonts";
		$this->cachepath = $cfg["paths"]["tmp"] . "/cache/ImageTexter";
		
		//Create a Checksum for the Requestet text
		$this->cachefile = md5(serialize($this)).".png";		
		
		if(!file_exists($this->cachepath . "/" . $this->cachefile)) {
			
			$image = $this->createStyledImage();
			
			imagepng($image, $this->cachepath . "/" . $this->cachefile);
		}
			
		$this->isRendered = true;
		
	}
	
	function createStyledImage() {
		
		if($this->style=="imageLink") {
			// Do Nothing more
			return $this->createImageFromText($this->text, $this->fontSize, $this->fontName, $this->fontColor, $this->bgColor, $this->rotation);
		
		}
		
		if($this->style=="photoLink") {
			
			$imgText = $this->createImageFromText($this->text, $this->fontSize, $this->fontName, $this->fontColor, $this->bgColor, $this->rotation, $this->borderSize, $this->borderColor);
			$txt_width = imagesx($imgText);
			$txt_height = imagesy($imgText);

			// Create New Image based on with and height
	        $image = imagecreatetruecolor($this->width, $this->height);
	        //imagealphablending($image,false);
			//$col=imagecolorallocatealpha($image,255,255,255,127);
			//imagefilledrectangle($image, 0, 0, $this->width, $this->height, $col);
			//imagealphablending($image,true);
			//imagesavealpha($image, true);
			
			//Load Background image and copy it to the generated Image
			if(is_file($this->bgImagePath)) {
				$imgBackground = imagecreatefromjpeg($this->bgImagePath);
				imagecopyresampled($image, $imgBackground, 0, 0, 0, 0, $this->width, $this->height, $this->width, $this->height);	
			}			
			//Copy the Text into the Image
			imagecopyresampled($image, $imgText, 0, $this->height - $txt_height -3, 0, 0, $txt_width, $txt_height, $txt_width, $txt_height);	

			return $image;
			/*
			//Background Image
			$watermark = imagecreatefrompng($this->bgImagePath);
			$bg_width = imagesx($watermark);
			$bg_height = imagesy($watermark);
			*/
		}
	}
	
	function createImageFromText($text="Your Text here", $fontSize = 12, $fontName="Arial", $fontColor="0x000000", $bgColor="0xffffff", $rotation=0, $borderSize=0, $borderColor="0xffffff") {

		$fontspath = dirname(__FILE__). "/fonts";

		if(file_exists($fontspath . "/" . $fontName . ".ttf")) {
			$fontpath = $fontspath . "/" . $fontName . ".ttf";
		}
		elseif(file_exists($fontspath . "/" . $fontName . ".otf")) {
			$fontpath = $fontspath . "/" . $fontName . ".otf";
		}
		
		/*
		echo "fontname:" . $fontName . "<br>";
		echo "fontpath:" . $fontpath;
		echo "fileexists:" . (file_exists($fontpath)?"Yes":"no");
		*/
		
		//See: http://ruquay.com/sandbox/imagettf/
		
		$refchar = "g|";
		
		//Find the Baseline of the Font and the maxiumum possible height of a char event if it is no used in the Text
        $font_bounds = ImageTTFBBox($fontSize, 0, $fontpath, $refchar);
		
        /*
         * See php-Manual http://ch.php.net/imagettfbbox
         * 
         * 0 lower left corner, X position 
         * 1 lower left corner, Y position
         * 2 lower right corner, X position
         * 3 lower right corner, Y position
         * 4 upper right corner, X position
         * 5 upper right corner, Y position
         * 6 upper left corner, X position
         * 7 upper left corner, Y position 
         */
		
		$font_baseline = $font_bounds[1];
		$font_height = max($font_bounds[1], $font_bounds[3]) - min($font_bounds[5], $font_bounds[7]);
		$font_left = min($font_bounds[0], $font_bounds[6]);
		
		/*
		echo "Font-Baseline: $font_baseline<br>";
		echo "Font-Height: $font_height<br>";
		echo "Font-Left: $font_left<br>";
		*/
		$text_height = 0;
		$text_width = 0;
		
		$text = str_replace("<br>", "\n", $text);
		$lines = explode("\n", $text);
		for($l=0; $l<count($lines); $l++) {

			//Determine the real font box for the Text (specialy the with, we alreade have de height and the basline
	        $text_bounds = ImageTTFBBox($fontSize, 0, $fontpath, $lines[$l]);
	        //$text_baseline = max($text_bounds[1], $text_bounds[3]); 
	        
	        $text_heightArr[$l] = max($text_bounds[1], $text_bounds[3]) - min($text_bounds[5], $text_bounds[7]);
	        $text_widthArr[$l] = max($text_bounds[2], $text_bounds[4]) - min($text_bounds[0], $text_bounds[6]);
			
	        //Add the Values to the total
	        $text_height+=$text_heightArr[$l];
	        $text_width=max($text_width, $text_widthArr[$l]);
			
		}
		
		
        /*
        print_r($text_bounds);
        echo "Text-width: $text_width<br>";
        echo "Text-height: $text_height<br>";
		*/

		if($rotation==0) {
			$x = 0; 
			$y = $font_height-$font_baseline;
			$imageWidth = $text_width+3;
			$imageHeight = $font_height * count($lines) + (count($lines)>1?count($lines) * $font_baseline:0);
		}
		if($rotation==90) {
			
			$x = $font_height-$font_baseline; 
			$y = $text_width+3;
			$imageWidth = $font_height * count($lines) + (count($lines)>1?count($lines) * $font_baseline:0);
			$imageHeight = $text_width+3;
		}
		  
		
        // Space if border is set
        $space = $borderSize;
        
        $image = imagecreatetruecolor($imageWidth+2*$space, $imageHeight+2*$space);
        
        imagealphablending($image,false);
		$col=imagecolorallocatealpha($image,255,255,255,127);
		imagefilledrectangle($image, 0, 0, $imageWidth+2*$space, $imageHeight+2*$space, $col);
		imagealphablending($image,true);
		
		/* Add Border */
		for($offset_y=0;$offset_y<(2*$space+1);$offset_y++) {
			for($offset_x=0;$offset_x<(2*$space+1);$offset_x++) {
				ImageTTFText($image, $fontSize, $rotation, $x+$offset_x, $y+$offset_y, $borderColor, $fontpath, $text);
			}
		}
				
		
		
		ImageTTFText($image, $fontSize, $rotation, $x+$space, $y+$space, $fontColor, $fontpath, $text);
		
        //imagealphablending($image, false);
		imagesavealpha($image, true);

		return $image;
		
	}
	
	function getImageUrl() {
		
		if(!$this->isRendered) $this->render();
		
		//Pfad im Filesystem, relativ zum index-File
		$fspath = str_replace(getcwd(), "", dirname(__FILE__));
		$fspath = str_replace("\\", "/", $fspath);
		if(substr($fspath,0,1)=="/") { $fspath = substr($fspath, 1); }
		
		$urldir = str_replace($_SERVER['QUERY_STRING'], "", $_SERVER['REQUEST_URI']);
		$urldir = str_replace("?", "", $urldir);
		
		//phpinfo();
		//echo "\n[ DEBUG ]FS-Pfad: $fspath\nURL-Dir:$urldir\n[ /DEBUG ]";
		
		$cfg = Runtime::getConfiguration();
		$file = $this->cachepath = $cfg["paths"]["tmp"] . "/cache/ImageTexter/" . $this->cachefile;
		
		
		//$url = $urldir . $fspath . "/cache/". $this->cachefile . "?".md5(microtime(false));
		$url = "tmp/cache/ImageTexter/". $this->cachefile . "?".md5_file($file);
		
		//die($url);
		return $url;
		
		
		
	}
}


?>